/**
 * drag-shift
 * Copyright (c) 2014 Vishal Kumar
 * Licensed under the MIT License.
 */
'use strict';
// console.log(123);
(function(factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {
    var IS_TOUCH_DEVICE = ('ontouchstart' in document.documentElement);
    /**
     * mouse move threshold (in px) until drag action starts
     * @type {Number}
     */
    var DRAG_THRESHOLD = 5;
    /**
     * to generate event namespace
     * @type {Number}
     */
    var counter = 0;

    /**
     * Javascript events for touch device/desktop
     * @return {Object}
     */
    var dragEvents = (function() {
        if (IS_TOUCH_DEVICE) {
            return {
                START: 'touchstart',
                MOVE: 'touchmove',
                END: 'touchend'
            };
        } else {
            return {
                START: 'mousedown',
                MOVE: 'mousemove',
                END: 'mouseup'
            };
        }
    }());

    $.fn.arrangeable = function(options) {
        var dragging = false;
        var $clone;
        var dragElement;
        var originalClientX, originalClientY; // client(X|Y) position before drag starts
        var $elements; // list of elements to shift between
        var touchDown = false;
        var leftOffset, topOffset;
        var eventNamespace;

        if (typeof options === "string") {
            // check if want to destroy drag-arrange
            if (options === 'destroy') {
                if (this.eq(0).data('drag-arrange-destroy')) {
                    this.eq(0).data('drag-arrange-destroy')();
                }

                return this;
            }
        }


        options = $.extend({
            "dragEndEvent": "drag.end.arrangeable"
        }, options);

        var dragEndEvent = options["dragEndEvent"];

        $elements = this;
        eventNamespace = getEventNamespace();

        this.each(function() {
            // bindings to trigger drag on element
            var dragSelector = options.dragSelector;
            var self = this;
            var $this = $(this);

            if (dragSelector) {
                $this.on(dragEvents.START + eventNamespace, dragSelector, dragStartHandler);
            } else {
                $this.on(dragEvents.START + eventNamespace, dragStartHandler);
            }

            function dragStartHandler(e) {
                // a mouse down/touchstart event, but still drag doesn't start till threshold reaches
                // stopPropagation is compulsory, otherwise touchmove fires only once (android < 4 issue)
                e.stopPropagation();
                touchDown = true;
                originalClientX = e.clientX || e.originalEvent.touches[0].clientX;
                originalClientY = e.clientY || e.originalEvent.touches[0].clientY;
                dragElement = self;
            }
        });

        // bind mouse-move/touchmove on document
        // (as it is not compulsory that event will trigger on dragging element)
        $(document).on(dragEvents.MOVE + eventNamespace, dragMoveHandler)
            .on(dragEvents.END + eventNamespace, dragEndHandler);

        function dragMoveHandler(e) {
            // console.log(touchDown);
            if (!touchDown) { return; }

            var $dragElement = $(dragElement);
            var dragDistanceX = (e.clientX || e.originalEvent.touches[0].clientX) - originalClientX;
            var dragDistanceY = (e.clientY || e.originalEvent.touches[0].clientY) - originalClientY;
            // console.log(222);
            if (dragging) {
                e.stopPropagation();
                var scrollH=0;
                scrollH=$('.main').scrollTop();
                $clone.css({
                    left: leftOffset + dragDistanceX,
                    top: topOffset + dragDistanceY-scrollH
                });

                shiftHoveredElement($clone, $dragElement, $elements);

                // check for drag threshold (drag has not started yet)
            } else if (Math.abs(dragDistanceX) > DRAG_THRESHOLD ||
                Math.abs(dragDistanceY) > DRAG_THRESHOLD) {
                $clone = clone($dragElement);
                // console.log(333);
                // initialize left offset and top offset
                // will be used in successive calls of this function
                leftOffset = dragElement.offsetLeft - parseInt($dragElement.css('margin-left')) -
                    parseInt($dragElement.css('padding-left'));
                topOffset = dragElement.offsetTop - parseInt($dragElement.css('margin-top')) -
                    parseInt($dragElement.css('padding-top'));

                // put cloned element just above the dragged element
                // and move it instead of original element
                $clone.css({
                    left: leftOffset,
                    top: topOffset
                });
                $dragElement.parent().append($clone);

                // hide original dragged element
                $dragElement.css('visibility', 'hidden');

                dragging = true;
            }
        }

        function dragEndHandler(e) {

            // console.log(dragging)
            if (dragging) {
                // remove the cloned dragged element and
                // show original element back
                e.stopPropagation();
                dragging = false;
                $clone.remove();
                dragElement.style.visibility = 'visible';

                $(dragElement).parent().trigger(dragEndEvent, [$(dragElement)]);
                var arr1=[];
                var id = $('.task_list>li')

                var fId = dragElement.getAttribute('id')

                $("#"+fId).parent().append(dragElement)
                console.log(id)
                for(var i=0;i<id.length;i++){
                    if(fId == id[i].id){
                        console.log(id[i])
                    }
                }

                // var data = {
                //     taskId: 0, // 任务主键id
                //     taskName: taskName, // 任务名称
                //     taskDesc: '', // 任务详情
                //     importantLevel: parseInt(importantLevel), //重要程度 0普通 1重要 2紧急 传数字类型
                //     createUser: h.createUser.userId.toString(), // 创建人
                //     manageUser: manageUser.toString(), //负责人
                //     taskStatus: '0', //任务状态
                //     createDate: createDate, //创建时间
                //     startDate: createDate, //开始时间
                //     endDate: endDate, //结束时间
                //     parentId: 0, //父任务Id
                //     progress: 0, //任务进度 传数字类型
                //     taskGrade: 0, // 评分
                //     completeDate: '', // 完成日期
                //     typeId: typeId, //任务类型id
                //     attachmentId: '', // 附件id
                //     attachmentName: '', // 附件名字
                //     participate: participate, //参与者 拼接用户id用，连接
                //     shared: '',//共享者 拼接用户id用，连接
                //     follow: 0//是否关注  取消关注2 关注1 默认 0
                // }

                // $.ajax({
                //     type: 'post',
                //     url: basePath + "task/addTaskManage",
                //     dataType: 'json',
                //     data: data,
                //     success: function (res) {
                //         if (res.flag) {
                //             var listData = $(_this).parents('.content_list_item').data('listData');
                //             var $listItem = $(_this).parents('.content_list_item');
                //
                //             // 重新渲染该列表下的任务
                //             initTaskItemList(listData.typeId, {}, $listItem);
                //             $(_this).parents('.edit-form').hide(0, function(){
                //                 h.resetTaskForm(this)
                //             });
                //             setP_contentScroll(_this);
                //         } else {
                //             $.message({
                //                 message: '新增任务失败',
                //                 type: 'danger'
                //             });
                //         }
                //     },
                //     error: function(err) {
                //         $.message({
                //             message: '新增任务失败',
                //             type: 'danger'
                //         });
                //     }
                // });


                // for (var i = 0; i < id.length; i++) {
                //     if(id!='todayBox'){
                //         arr1.push(id.eq(i).attr('id'));
                //     }
                // }
                // var infoCenterOrder=  arr1.join(',');
                // infoCenterOrder = infoCenterOrder+",";
                // $.ajax({
                //     type:'post',
                //     url:'/infoCenter/setInfoCenterOrder',
                //     data:{
                //         infoLeftOrder: infoCenterOrder
                //     },
                //     dataType:'json',
                //     success:function (res) {
                //         console.log(res);
                //     }
                // })
                // window.location.reload()
            }

            touchDown = false;
        }
        // console.log(arr1);
        function destroy() {
            $elements.each(function() {
                // bindings to trigger drag on element
                var dragSelector = options.dragSelector;
                var $this = $(this);

                if (dragSelector) {
                    $this.off(dragEvents.START + eventNamespace, dragSelector);
                } else {
                    $this.off(dragEvents.START + eventNamespace);
                }
            });

            $(document).off(dragEvents.MOVE + eventNamespace)
                .off(dragEvents.END + eventNamespace);

            // remove data
            $elements.eq(0).data('drag-arrange-destroy', null);

            // clear variables
            $elements = null;
            dragMoveHandler = null;
            dragEndHandler = null;
        }

        this.eq(0).data('drag-arrange-destroy', destroy);
    };

    function clone($element) {//位置
        var $clone = $element.clone();
        var scrollH=0;
        scrollH=$('.main').scrollTop();

        $clone.css({
            position: 'absolute',
            width: $element.width(),
            height: $element.height(),
            'z-index': 100000 // very high value to prevent it to hide below other element(s)
        });

        return $clone;
    }

    /**
     * find the element on which the dragged element is hovering
     * @return {DOM Object} hovered element
     */
    function getHoveredElement($clone, $dragElement, $movableElements) {
        var cloneOffset = $clone.offset();
        var cloneWidth = $clone.width();
        var cloneHeight = $clone.height();
        var cloneLeftPosition = cloneOffset.left;
        var cloneRightPosition = cloneOffset.left + cloneWidth;
        var cloneTopPosition = cloneOffset.top;
        var cloneBottomPosition = cloneOffset.top + cloneHeight;
        var $currentElement;
        var horizontalMidPosition, verticalMidPosition;
        var offset, overlappingX, overlappingY, inRange;

        for (var i = 0; i < $movableElements.length; i++) {
            $currentElement = $movableElements.eq(i);

            if ($currentElement[0] === $dragElement[0]) { continue; }

            offset = $currentElement.offset();

            // current element width and draggable element(clone) width or height can be different
            horizontalMidPosition = offset.left + 0.5 * $currentElement.width();
            verticalMidPosition = offset.top + 0.5 * $currentElement.height();

            // check if this element position is overlapping with dragged element
            overlappingX = (horizontalMidPosition < cloneRightPosition) &&
                (horizontalMidPosition > cloneLeftPosition);

            overlappingY = (verticalMidPosition < cloneBottomPosition) &&
                (verticalMidPosition > cloneTopPosition);

            inRange = overlappingX && overlappingY;

            if (inRange) {
                return $currentElement[0];
            }
        }
    }

    function shiftHoveredElement($clone, $dragElement, $movableElements) {
        var hoveredElement = getHoveredElement($clone, $dragElement, $movableElements);

        if (hoveredElement !== $dragElement[0]) {
            // shift all other elements to make space for the dragged element
            var hoveredElementIndex = $movableElements.index(hoveredElement);
            var dragElementIndex = $movableElements.index($dragElement);
            if (hoveredElementIndex < dragElementIndex) {
                $(hoveredElement).before($dragElement);
            } else {
                $(hoveredElement).after($dragElement);
            }

            // since elements order have changed, need to change order in jQuery Object too
            shiftElementPosition($movableElements, dragElementIndex, hoveredElementIndex);
        }
    }

    function shiftElementPosition(arr, fromIndex, toIndex) {
        var temp = arr.splice(fromIndex, 1)[0];
        return arr.splice(toIndex, 0, temp);
    }

    function getEventNamespace() {
        counter += 1;

        return '.drag-arrange-' + counter;
    }

}));